//
//  LGSearchControllerViewController.m
//  ALS-02
//
//  Created by guomianxiang on 16/11/8.
//  Copyright © 2016年 guomianxiang. All rights reserved.
//

#import "LGSearchControllerViewController.h"
#import "LGControllerInfoViewController.h"

#import "udpManger.h"

#import "LGDCTableHead.h"
#import "ALSBarButton.h"

#import "UIColor+LG.h"
@interface LGSearchControllerViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
//@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *actitvityIndicator;

@property (strong, nonatomic) NSMutableArray <NSMutableArray <LGDCCellContent *>*>* tableDataArr;
@property (strong, nonatomic) NSMutableArray <LGController *>*controllers;

@property (assign, nonatomic) NSUInteger controller_count;
@property (strong, nonatomic) udpManger *udpManger_1;
@property (strong, nonatomic) udpManger *udpManger_2;


@property (nonatomic ,strong) NSTimer *timer;

@property (strong, nonatomic) LGControllerManager *manager;

@property (strong, nonatomic) dispatch_queue_t queue;
@end

@implementation LGSearchControllerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
    [self setupNav];
    [self setupNotification];
    _controllers = [NSMutableArray array];
    _tableDataArr = [NSMutableArray arrayWithObjects:[NSMutableArray array], nil];
    k_registerNib(self.tableView);
}


#pragma mark - setup
- (void)setup {
    _queue = dispatch_queue_create("search", DISPATCH_QUEUE_SERIAL);
    self.automaticallyAdjustsScrollViewInsets = NO;

    
}

- (void)setupNav {
    self.navigationItem.title = @"自动添加控制器";
    
    UIButton *back = [ALSBarButton backButtonWithTitle:nil];
    [back addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:back];
}

- (void)setupNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getControllerNots:) name:ALSSearchControllerNotification object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self searchController];
    
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:activityView];
    self.navigationItem.rightBarButtonItem = item;
    [activityView startAnimating];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self sacnStop];
    [self.timer invalidate];
}

- (LGControllerManager *)manager {
    if (_manager == nil) {
        _manager = [[LGControllerManager alloc]init];
    }
    return _manager;
}

- (void)searchController {
    [self.udpManger_1 openUDPServer:@"224.0.0.2" port:8003];
    [self.udpManger_2 openUDPServer:@"224.0.0.2" port:8061];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:200 target:self selector:@selector(sacnStop) userInfo:nil repeats:NO];
}

- (void)sacnStop{
    [self.udpManger_1 close];
    [self.udpManger_2 close];
    self.navigationItem.rightBarButtonItem = nil;
}

- (void)getControllerNots:(NSNotification *)not{
    
    __weak typeof(self) weakSelf = self;
    
    dispatch_async(_queue, ^{
        LGController *controll = not.userInfo[ALSSearchControllerNotificationUserInfoKey];
        
        for (int i=0; i<weakSelf.controllers.count; i++) {
            if ([weakSelf.controllers[i].mac isEqualToString:controll.mac]) {
                return;
            }
        }
        
        if ([DCMI isExistsItemWithSN:controll.sn]) {
            controll.exist = YES;
        }else {
            controll.exist = NO;
        }
        
        [weakSelf.controllers addObject:controll];
        LGDCCellContent *content = [LGDCCellContent transfromCellContentArrWithSearchResultController:controll];
        if (kScreen_W > 320) {
            
            int number = (weakSelf.tableDataArr[0].count) % 3 + 1;

            content.image = [UIImage imageNamed:[NSString stringWithFormat:@"门禁%i",number]];
        }
        
        [weakSelf.tableDataArr[0] addObject:content];
        //回到主线程刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [weakSelf.tableView reloadData];
            
        });

        
    });
}
#pragma mark - 懒加载

- (udpManger *)udpManger_1 {
    if (_udpManger_1 == nil) {
        _udpManger_1 = [[udpManger alloc]init];
    }
    return _udpManger_1;
}

- (udpManger *)udpManger_2 {
    if (_udpManger_2 == nil) {
        _udpManger_2 = [[udpManger alloc]init];
    }
    return _udpManger_2;
}

#pragma mark - UITableViewDataSource

k_tableViewDataSourceAndCellHeight(tableDataArr, nil);

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.controllers[indexPath.row].exist == YES) {
        return;
    }
    
    [self performSegueWithIdentifier:@"searchVCToInfoTableVC" sender:self.controllers[indexPath.row]];
    [self sacnStop];

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    LGControllerInfoViewController *infoTVC = segue.destinationViewController;

    infoTVC.addControllerItem = sender;
}


@end
